from rest_framework import viewsets, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from operation.models import UserFav, UserAddress, UserBehavior
from operation.serializers import UserFavDetailSerializer, UserFavSerializer, AddressSerializer
from utils.mixins import CustomCreateModelMixin, CustomListModelMixin, CustomRetrieveModelMixin, \
    CustomDestroyModelMixin, CustomUpdateModelMixin
from utils.permissions import IsOwnerOrReadOnly
from utils.response import APIResponse


class UserFavViewset(CustomCreateModelMixin, CustomListModelMixin, CustomRetrieveModelMixin,
                     CustomDestroyModelMixin, viewsets.GenericViewSet):
    """
    list:
        获取用户收藏列表
    retrieve:
        判断某个商品是否已经收藏
    create:
        收藏商品
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    lookup_field = "good_id"

    def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)

    def get_serializer_context(self):
        return {
            'format': self.format_kwarg,
            'view': self
        }

    def perform_create(self, serializer):
        instance = serializer.save()
        good = instance.good
        good.fav_num += 1
        good.save()

    def perform_destroy(self, instance):
        instance = self.get_object()
        good = instance.good
        good.fav_num -= 1
        good.save()
        instance.delete()

    def get_serializer_class(self):
        if self.action == "list":
            return UserFavDetailSerializer
        elif self.action == "create":
            return UserFavSerializer

        return UserFavSerializer


class AddressViewset(CustomCreateModelMixin, CustomListModelMixin, CustomUpdateModelMixin, CustomRetrieveModelMixin,
                     CustomDestroyModelMixin, viewsets.GenericViewSet):
    """
    收货地址管理
    list:
        获取收货地址
    create:
        添加收货地址
    update:
        更新收货地址
    delete:
        删除收货地址
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = AddressSerializer

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)
    #
    # def perform_create(self, serializer):
    #     serializer.save()
